# -*- coding: utf-8 -*-
#
# @Author: CPS
# @email: 373704015@qq.com
# @Date: 
# @Last Modified by: CPS
# @Last Modified time: 2021-04-12 03:27:20.556970
# @file_path "D:\CPS\IDE\JS_SublmieText\Data\Packages\CPS\core"
# @Filename "update_channel.py"
# @Description: 功能描述
#
if ( __name__ == "__main__"):
    pass

import sublime
import sublime_plugin
import os,sys,json

from .utils import env
from .utils.logging import log
from .utils import json5

FLAG = True

def init():
    #检查所有必要的文件夹
    FLAG = check_floders()

def floder_list():
    return {
        'channel_v3_file':env.channel_file_path(),
        'user_path':os.path.join(sublime.packages_path(),'User'),
        'Control.sublime-settings':os.path.join(sublime.packages_path(),'User','Package Control.sublime-settings'),
    }

# 验证各个文件夹、文件是否存在，任意一个不存则，则返回False
def check_floders():
    res = True

    # 各个要验证的文件夹
    try:
        for each in floder_list().values():
            if not env.check_file_exists(each):
                res = False
                log('update_channel','缺少必要的文件: '+ each,'无法继续执行')
                break
    except Exception as error:
        log("Error during copy")

    return res

# 创建空的Control.sublime-settings 文件
def create_Control_settings_file():
    newFile = open(
        pcfile,
        "w",
        encoding='utf8'
        )
    newFile.close()

# 导入离线的 channel文件
def update_channel():
    # 检查文件
    if not check_floders():
        return False

    # 将channel_v3_file路径写到配置文件
    file_list = floder_list()
    channel_v3_file = file_list['channel_v3_file']
    currt_settings_file = file_list['Control.sublime-settings']

    #读取现有配置文件
    with open(currt_settings_file,'r',encoding='utf8') as f:
        currt_settings = json5.load(f)

        # 如果当前配置不存在 channels 这个键，则马上创建
        if not currt_settings.get('channels'):
            currt_settings['channels'] = [channel_v3_file]

        else:
            #判断是否已存在需要添加的 channel
            if not channel_v3_file in currt_settings['channels']:
                currt_settings['channels'].append(channel_v3_file)

        print('更新文件成功')

    # 写入新文件
    with open(currt_settings_file,'w',encoding='utf8') as f:
        json.dump(currt_settings,f,sort_keys=True,indent='  ',ensure_ascii=False)
